//
//  SCWebViewController.swift
//  weibo
//
//  Created by 阿城 on 15/12/6.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit
import SVProgressHUD

    let AppKey = "334216144"
    let Redirect_uri = "http://www.baidu.com/"
    let AppSecret = "c225f6ef1ab25afbea06510c4a9efa30"

class SCWebViewController: UIViewController,UIWebViewDelegate {

    
    private lazy var web = UIWebView()
    
    var accessTokenClosure: ((token: String)->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view = web
        //https://api.weibo.com/oauth2/authorize?client_id=334216144&redirect_uri=http://www.baidu.com/
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        printLog(urlStr)
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        web.loadRequest(request)
        
        web.delegate = self
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    }

    @objc private func dismiss(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func autoFill(){
    web.stringByEvaluatingJavaScriptFromString( "document.getElementById('userId').value = 'yohtr35601@163.com' , document.getElementById('passwd').value = 'qw1987'")
    }
    
    // MARK: - webView Delegate
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = request.URL!.absoluteString
//        printLog(urlStr)
        
        if !urlStr.hasPrefix("http://www.baidu.com/?") {
            return true
        }
        
        let codeStr = request.URL!.query!
        
        if codeStr.hasPrefix("code"){
            
            let code = codeStr.substringFromIndex("code=".endIndex)
            
            
            HTTPClient.shareManager.getUserData(code, callBack: { (seccess) -> () in
                if seccess {

                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(kSwitchVcNotifcation, object: self)
                    })
                }else{
                    printLog("wrong")
                }
            })
            
            //printLog(code)
        }
        
        return false
        
    }

    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

   
}
